<?php
/**
 * Created by PhpStorm.
 * User: jifee8505
 * Date: 2018/9/7
 * Time: 上午11:52
 */

namespace common\components;

use Yii;
use yii\base\Exception;
use api\models\redis\ActiveRecordRedis;

class ResponseEvent
{
    public function createApiResponseAt()
    {
        $uri = parse_url($_SERVER["REQUEST_URI"]);
        if (strpos($uri["path"], $_SERVER["SCRIPT_NAME"]) !== false) {
            $method = substr($uri["path"], strlen($_SERVER["SCRIPT_NAME"]));
        } elseif (strpos($uri["path"], dirname($_SERVER["SCRIPT_NAME"])) !== false) {
            $method = substr($uri["path"], strlen(dirname($_SERVER["SCRIPT_NAME"])));
        }
        // 接口响应时间
        if (!empty($method)) {
            $method = strtr($method, '/', '_');
            $response_at = microtime(true) - MICROTIME;
            self::createRedisApiResponseAt('api_method', $method, $response_at);
        }
    }

    public static function createRedisApiResponseAt($key, $method, $response_at)
    {
        try {
            $api_method_at = ActiveRecordRedis::getHash($key . '::at', [$method]);
            $at = !empty($api_method_at[$method]) ? $api_method_at[$method] + $response_at : $response_at;
            ActiveRecordRedis::setHash($key . '::at', [$method => $at]);

            $api_method_num = ActiveRecordRedis::getHash($key . '::num', [$method]);
            $num = !empty($api_method_num[$method]) ? $api_method_num[$method] : 0;
            $num++;
            ActiveRecordRedis::setHash($key . '::num', [$method => $num]);

        } catch (Exception $e) {
            Yii::warning($e);
        }
    }
}